import 'dart:io';
import 'package:epubx/epubx.dart';
import 'package:my_ebook_app/models/book.dart';
import 'package:path_provider/path_provider.dart';
import 'package:dio/dio.dart';

class EpubParser {
  static Future<List<String>> parseEpub( String title, String epubPath) async {
    try {
      // 首先检查文件是否存在
      if (!await File(epubPath).exists()) {
        throw Exception("EPUB文件不存在: $epubPath");
      }
      // 读取文件为字节数组
      final bytes = await File(epubPath).readAsBytes();
      // 解析 EPUB
      final epubBook = await EpubReader.readBook(bytes);
      final chapters = <String>[];
      int index = 0;
      while (index < epubBook.Chapters!.length) {
        final chapter = epubBook.Chapters![index];
        if (chapter.SubChapters!.length > 0){
          break;
        }
        index++;
      }
      // 递归提取所有章节内容
      if (index < epubBook.Chapters!.length) {
        _extractChapters(epubBook.Chapters!.sublist(index), chapters);
      }
      for (int i = 0; i<chapters.length;i++){
        chapters[i] = chapters[i].replaceFirst(title, "");
      }
      return chapters;
    } catch (e) {
      print('EPUB解析错误: $e');
      return [];
    }
  }

  static Future<String> downloadAndSaveEpub(ReadingBook book) async {
    try {
      final appDir = await getApplicationDocumentsDirectory();
      final fileName = book.title;
      final filePath = '${appDir.path}/$fileName';

      final response = await Dio().get(
        book.epubPath,
        options: Options(responseType: ResponseType.bytes),
      );

      await File(filePath).writeAsBytes(response.data);
      print('EPUB下载成功: $filePath');
      return filePath;
    } catch (e) {
      print('EPUB下载错误: $e');
      rethrow;
    }
  }

  static void _extractChapters(List<EpubChapter>? chapters, List<String> output) {
    if (chapters == null) return;

    for (int i = 0; i < chapters.length; i++) {
      final chapter = chapters[i];
      String? htmlContent = chapter.HtmlContent;
      output.add(_extractTextFromHtml(htmlContent!));
      // 递归处理子章节
      _extractChapters(chapter.SubChapters, output);
    }
  }

  static String _extractTextFromHtml(String html) {
    html = html.replaceAll(
      RegExp(r'<span\s+class="math-super">.*?</span>', caseSensitive: false, dotAll: true),
      '',
    );

    html = html.replaceAll(
      RegExp(
        r'<[pр][^>]*>\s*<a\s+[^>]*?href="#n[kh]\d+"[^>]*?id="n[hk]\d+"[^>]*?>注</a>\s*.*?</[pр]>',
        caseSensitive: false,
        dotAll: true,
      ),
      '',
    );
    // <p>标签以便后续处理段落
    String text = html.replaceAllMapped(RegExp(r'<p[^>]*>'), (match) => '\n<p>');

    // 去除其他HTML标签
    text = text.replaceAll(RegExp(r'<[^>]*>'), '');

    return text
        .replaceAll(RegExp(r'\s{2,}'), ' ')
        .replaceAll(RegExp(r'\n{2,}'), '\n\n')
        .trim();
  }

}